<template>
  <div class="questionBankDetails" v-loading="loading">
    <div class="sideNav">
      <SideNav :width="450" :menuList="menuList" :fold="true">
        <template #timu>
          <!-- <div>题目列表</div> -->
          <QuestionList></QuestionList>
        </template>
        <template #taolun>
          <Discussion :questionId="questionId as string" :textarea="textarea" :commentInput="commentInput"></Discussion>
        </template>
        // <template #jilu>
          // <div>记录</div>
          // </template>
      </SideNav>
    </div>
    <el-container>
      <!-- 主体 -->
      <el-main>
        <!-- 主体内容 -->
        <div class="main">
          <!-- 题目详情 -->
          <div class="main-topic">
            <!-- 题目标题 -->
            <div class="main-topic-header">
              <span class="iconfont icon-likesprogramshouye"></span>
              <span>{{ questionBankData?.exercisesId }}</span>
              <span class="main-topic-title-content" v-html="questionBankData?.title || '加载中...'"></span>
              <!-- <span class="main-topic-title-score">({{ questionBankData?.questions.score }})</span> -->
            </div>
            <!-- 题目信息 -->
            <div class="main-topic-questionInfo">
              <!-- 题目类型和标签 -->
              <div class="main-topic-title">
                <div class="main-topic-font">简答题:</div>
                <!-- <div class="main-topic-font" v-for="question in questionBankData?.questions" :key="question.recId">
                  {{ question.questionType }}
                </div> -->
                <div>
                  <el-tag type="danger" style="margin-left: 15px;">{{ questionBankData?.courseInfo.courseName
                    }}</el-tag>
                  <el-tag type="success">{{ questionBankData?.chapterInfo.chapterName }}</el-tag>
                  <el-tag type="primary" v-for="knowledge in questionBankData?.knowledge" :key="knowledge.recordId">
                    {{ knowledge.knowledgeContent }}</el-tag>
                </div>
              </div>
              <!-- 题目描述 -->
              <div class="main-topic-questionStem">
                <div class="main-topic-font">题目描述:</div>
                <div class="main-topic-questionStem-content" v-html="questionBankData?.questionStem"></div>
              </div>
              <!-- 题目问题区 -->
              <div class="main-topic-question">
                <h4>问题:</h4>
                <div class="main-topic-question-content" v-for="question in questionBankData?.questions"
                  :key="question.displayOrder">
                  ({{ question.displayOrder }}) <span v-html="question.questionTitle"></span>

                </div>
              </div>
            </div>
          </div>

          <!-- 答题区 -->
          <div class="main-working">
            <!-- 编辑器容器 -->
            <div class="main-working-working">
              <div class="main-working-working-content" v-for="question in questionBankData?.questions" :key="question.displayOrder">
                  <div class="main-working-font">
                    ({{ question.displayOrder }}) 
                    <span v-html="question.questionTitle"></span>
                  </div>
                  <EditorComponent class="editor" v-model="question.userAnswerHtml" ref="editorComponent" placeholder="请输入内容..."/>
              </div>
              
            </div>
            <!-- 解析区 -->
            <div class="main-working-analysis-box">
              <div class="main-working-analysis" v-show="showAnalysis">
                <div class="main-working-analysis-score">
                  <div class="main-topic-font">
                    Ai打分: 
                  </div>
                  <div> {{ Math.floor(questionResult?.score) }}分</div>

                </div>
                <div>
                  <div class="main-topic-font">Ai评语: </div>
                </div>

                <div class="main-topic-font">答案：</div>
                <div v-for="questions in questionResult?.question" :key="questions.recId">
                  ( {{ questions?.displayOrder }}) {{ questions?.answer }}
                </div>
                <div class="main-topic-font">解析：</div>
                <div v-for="questions in questionResult?.question" :key="questions.recId" v-html="questions.analysis">
                </div>
              </div>
            </div>
            <!-- 提交按钮区 -->
            <div class="main-working-button" v-if="SubmitButton">
              <el-button type="primary" plain @click="handSave">保存</el-button>
              <el-button type="warning" plain @click="checkAnswers">提交</el-button>
            </div>
            <div class="main-working-button" v-else>
              <el-button type="success" plain @click="nextQuestion">上一题</el-button>
              <el-button type="danger" plain @click="handSave">随机一题</el-button>
              <el-button type="success" plain @click="nextQuestion">下一题</el-button>
            </div>
          </div>

        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts">
// 导包
import { computed, ref, onMounted, defineComponent, toRaw } from 'vue';
import { ElMessage } from 'element-plus';
import EditorComponent from '@/components/EditorComponent.vue';
import { useRoute } from 'vue-router'; // 导入 useRouter
import { useQuestionBankDataStore } from '@/store/modules/questionBank/questionbankdata.ts'
import { storeToRefs } from 'pinia';
import { QuestionBankApi } from '@/api/QuestionBank/QuestionBank.ts';
import { SideNavMenu } from '@/components/SideNav.vue';
import { ExampleParams, GradingResult } from '@/types/QuestionBankType.ts';
import Discussion from '@/components/questionBank/Discussion.vue'
import QuestionList from '@/components/questionBank/QuestionList.vue'
import { userApi } from '@/api/Users';
import { UserData } from '@/types/UserData';

export default defineComponent({
  name: 'questionBankDetails',
})
</script>

<script lang="ts" setup>


const menuList = ref<SideNavMenu[]>([
  // { iconName: 'icon-likesprograma-shangyibu1', titleText: '返回', onClick: () => { } },
  { iconName: 'icon-likesprogramliebiao', titleText: '题目', slotName: 'timu' },
  { iconName: 'icon-likesprogramduihuakuang', titleText: '讨论', slotName: 'taolun', onClick: () => { } },
  // { iconName: 'icon-likesprogramshijian', titleText: '记录', slotName: 'jilu', onClick: () => { } },
]);

// pinia数据
const questionListData = useQuestionBankDataStore();
questionListData.restoreData();
// 获取pinia数据
const { questionBankData } = storeToRefs(questionListData);
// 当前题目
const currentQuestion = ref(null);
// 当前题目索引
const questionIndex = ref(0);

// 监听数据变化(使用 $subscribe把数据保存到本地)
// questionStore.$subscribe((mutation, state) => {
//     localStorage.setItem('questionBankData',JSON.stringify(state.questionBankData))
// })


//// 获取路由id参数
const route = useRoute();
const questionId = route.params.topicId;
// console.log('路由传递id：', questionId);

// 评论
const textarea = ref('')
// 评论输入框引用
const commentInput = ref<HTMLElement | null>(null);

// 富文本编辑器数据 测试显示
const editorData = ref('');
const editorComponent = ref(null);
// 题目分析显示/隐藏
const showAnalysis = ref(false);
// 提交按钮显示/隐藏
const SubmitButton = ref(true);
// 用户信息
const userData = ref<UserData>(null);
// 接收后端返回的信息
const questionResult = ref<GradingResult>()
// 加载loading
const loading = ref(false)

// 提交答案(改卷功能)
const checkAnswers = () => {
  // console.log('用户答案:', editorComponent.value);

  // 修改时直接操作
  questionBankData.value.questions.forEach(q => {
    const temp = document.createElement('div');
    temp.innerHTML = q.userAnswerHtml || '';
    q.userAnswerText = (temp.textContent || temp.innerText || '').trim();
  });

console.log('处理后的数据:', questionBankData.value);

  loading.value = true;
  // 构造请求参数
  const params: ExampleParams = {
    userId: userData.value?.userId,
    exercisesId: questionBankData.value?.exercisesId,
    userAnswer: questionBankData.value.questions.map(q => q.userAnswerText || q.userAnswerHtml)
  };
  // console.log('用户答案'+params.userAnswer);
  // 
  // 调用 API 并处理数据
  QuestionBankApi.checkAnswers(params).then((res) => {
    // gradingResult.value = res;
    questionResult.value = res;

    if (questionResult.value && Array.isArray(questionResult.value.question)) {
      questionResult.value.question.forEach((question) => {
        question.answer = (JSON.parse(question.answer)).answer;
        console.log(question.answer);
      });
    }
    // SubmitButton.value = false;
    showAnalysis.value = true;

    ElMessage.success('提交成功');
    loading.value = false;
  });
};

// 方法

// const intScore = computed(() => Math.floor(questionResult.value.score));
//获取题库数据存储渲染页面
const getChangeQuestion = () => {
  // 确保 store 已初始化


  try {
    // 1. 先尝试从本地存储恢复数据
    questionListData.restoreData();

    // 2. 检查是否有数据
    if (!questionListData.questionBankData) {
      console.warn('本地没有题库数据');
      return null;
    }

    // 返回前验证数据结构
    if (typeof questionListData.questionBankData !== 'object') {
      throw new Error('题库数据格式错误');
    }

    // 如果已有数据，直接返回
    return questionListData.questionBankData;
  } catch (error) {
    console.error('获取题目数据失败:', error);
    throw error;
  }
}
// watch(
//   () => questionStore.questionBankData,
//   (newList) => {
//     if (newList.length > questionIndex.value) {
//       currentQuestion.value = newList[questionIndex.value]; // 更新当前题目
//     } else {
//       currentQuestion.value = null;
//     }
//   },
//   { immediate: true }
// );

// 切换到下一题
const nextQuestion = () => {
  if (questionIndex.value < questionBankData.value.questions.length - 1) {
    questionIndex.value++;
  } else {
    alert('已经是最后一题了！');
  }
};
// 保存
const handSave = () => {
  ElMessage.success('保存成功');
  // questionBankData.value. = editorComponent.value.getText();
}

//计算属性
// 输入框没有写入内容时，按钮不可点击
// const isButtonDisabled = computed(() => {
//   return textarea.value.trim() === '';
// });

//
onMounted(async () => {
  // 获取题目列表
  getChangeQuestion();
  try {
    const res = await userApi.getLoginUserData();
    if (res) {
      userData.value = res;
      // console.log(userData.value);
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } catch (error) {
    ElMessage.error('获取用户信息时出错');
    console.error(error);
  }
});

</script>

<style src="@/assets/icons/iconfont.css" scoped />

<style scoped>
/* 基础样式 */
.questionBankDetails {
  width: 100%;
  height: 100%;
  color: #24292e;
  background-color: var(--bg-color);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: var(--text-color);
  box-sizing: border-box;
  display: flex;
  justify-items: center;
  align-items: center;
}

.sideNav {
  flex-shrink: 0;
  height: 100%;
}

/* .sideNav-menu{
  width: 100%;
} */

/* 容器布局 */
.el-container {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  /* overflow: hidden; */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background-color: var(--card-bg);
}

.el-tag {
  margin-left: 0;
  margin-right: 10px;
  margin-top: 10px;
  font-weight: 500;
  height: 28px;
  line-height: 26px;
}

/* 主体内容 */
.el-main {
  padding: 0;
  display: flex;
  flex-direction: column;
  flex: 1;
  background-color: var(--bg-color);
}

.main {
  display: flex;
  flex: 1;
  padding: 20px;
  gap: 20px;
  height: calc(100% - 40px);
  /* 减去padding */
}

/* 头部样式 */
.main-topic-header {
  display: flex;
  margin-top: 1px;
  align-items: center;
  width: 100%;
  color: #6c757d;
  font-size: 20px;
  font-weight: bold;
  font-family: Arial, Helvetica, sans-serif;
  border-bottom: 1px solid #6c757d;
}

.main-topic-title-content {
  margin-left: 10px;
}

.main-topic-title-score {
  margin-left: 10px;
}

.iconfont {
  margin-right: 10px;
  font-size: 40px;
  color: #007bff;
}

/* 题目区域 */
.main-topic {
  flex: 1;
  background-color: var(--card-bg);
  border-radius: 8px;
  padding: 0px 20px 20px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  height: 100px;
  background-color: rgba(255, 255, 255, .5);
  backdrop-filter: blur(2rem);
  -webkit-backdrop-filter: blur(2rem);
  -moz-backdrop-filter: blur(2rem);
  -ms-backdrop-filter: blur(2rem);
}

.main-topic {
  float: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  /* 确保容器有明确高度 */
  font-size: 20px;
  color: var(--primary-color);
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
}

.main-topic-title {
  font-size: 18px;
  margin: 15px 0 10px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  display: flex;
  align-items: center;
}

.main-topic-questionStem,
.main-topic-question {
  margin-bottom: 20px;
}

.main-topic-question-content {
  display: flex;
}

.main-topic-questionStem,
.main-topic-question {
  font-size: 16px;
  margin: 25px 0 10px 0;
  padding-bottom: 5px;
  color: var(--text-color);
}

.main-topic-questionStem {
  margin-top: 15px;
}

.main-topic-questionInfo {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
  /* 防止滚动条遮挡内容 */
}

.main-topic-font {
  display: flex;
  margin-top: 10px;
  color: #24292e;
  font-size: 17.5px;
  font-weight: bold;
  font-family: Arial, Helvetica, sans-serif;
}

/* 标签按钮区域 */
.main-topic-button {
  width: 100%;
  height: 50px;
  /* border: #24292e solid 1px; */
  flex-shrink: 0;
  margin-top: auto;
  align-items: center;
  /* border-radius: 10px; */
  padding: 5px;
  /* background-color: rgb(255, 255, 255); */
  background-color: #F2F6FC;
  margin-top: 10px;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
}

.main-topic-tag {
  padding: 15px;
  border-top: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid rgba(200, 200, 200, .6);
}

.main-topic-tag:hover {
  background-color: var(--primary-light);
}

.main-topic-tag .iconfont {
  transition: transform 0.3s ease;
}


/* 答题区域 */
.main-working {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--card-bg);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.main-working-working {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  height: 300px;
  border-bottom: 1px solid var(--border-color);
}

.main-working-working-content{
  height: 50%;
  border-bottom: 2px solid #6c757d;
  /* border-top: 2px solid #6c757d; */
  margin-bottom: 20px;
}

.main-working-font{
  display: flex;
  justify-content: flex-start;
  /* margin-bottom: 20px; */
  /* margin-top: 50px; */
  /* padding-bottom: 10px; */
}

.main-working-analysis-box {
  padding-right: 20px;
}

.main-working-analysis {
  padding: 1px 1px 20px 20px;
  background-color: #f9f9f9;
  border-top: 1px solid var(--border-color);
  transition: all 0.3s ease;
  height: 300px;
  width: 100%;
  overflow-y: auto;
  /* 垂直溢出时显示滚动条 */
  margin-bottom: 10px;
}

.main-working-analysis-score {
  display: flex;
  align-items: baseline;
}

.main-working-button {
  width: 100%;
  height: 50px;
  /* flex-shrink: 0; */
  /* margin: 10px; */
  align-items: center;
  /* padding: 5px; */
  /* background-color: rgb(255, 255, 255); */
  background-color: #F2F6FC;
  /* overflow: hidden; */
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}


/* 评论区域 */
.el-input-box {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-top: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.el-input-box button {
  padding: 8px 16px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.el-input-box button:hover {
  background-color: #3a56e8;
}

.el-input-box button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.review-list {
  max-height: 200px;
  overflow-y: auto;
  margin-top: 15px;
}

.review-item {
  padding: 12px 0;
  border-bottom: 1px solid var(--border-color);
}

.review-user {
  font-weight: 600;
  color: var(--text-color);
}

.review-content {
  color: var(--text-color);
  margin: 5px 0;
}

.review-time {
  color: var(--text-light);
  font-size: 12px;
}

/* 底部按钮 */
.el-footer {
  padding: 15px 30px;
  background-color: var(--card-bg);
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-footer .el-button {
  padding: 0;
  border: none;
  background: none;
}

.el-footer .iconfont {
  font-size: 40px;
  color: var(--primary-color);
  transition: transform 0.3s;
}

.el-footer .iconfont:hover {
  transform: scale(1.1);
}

.el-footer .el-button--primary,
.el-footer .el-button--warning {
  padding: 10px 24px;
  font-size: 16px;
  border-radius: 6px;
  font-weight: 500;
  height: auto;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .main {
    flex-direction: column;
  }

  .main-topic,
  .main-working {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .el-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px;
  }

  .header-title {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-title .iconfont {
    margin-bottom: 10px;
  }

  .header-tag h2 {
    font-size: 20px;
  }

  .el-footer {
    padding: 10px 15px;
  }

  .el-footer .el-button--primary,
  .el-footer .el-button--warning {
    padding: 8px 16px;
    font-size: 14px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.main-topic-tag,
.review-item {
  animation: fadeIn 0.3s ease forwards;
}
</style>